package com.gxm.练习.string;


import com.google.common.collect.Maps;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo2 {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());

        List<WeekBoundary> weekBoundaries = new ArrayList<>();
        Map<String, WeekBoundary> weekBoundariesMap = Maps.newLinkedHashMap();
        for (LocalDate date = firstDayOfMonth; !date.isAfter(firstDayOfMonth.plusMonths(1)); date = date.plusDays(1)) {
            // 找到当前日期所在周的第一天（周一）
            LocalDate startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

            // 找到该周最后一天（周日）
            LocalDate endOfWeek = startOfWeek.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

            // 转换为 LocalDateTime 并添加到结果列表
            LocalDateTime startOfWeekDateTime = LocalDateTime.of(startOfWeek, LocalTime.MIN);
            LocalDateTime endOfWeekDateTime = LocalDateTime.of(endOfWeek, LocalTime.MAX);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String startOfWeekDateTimeStr = startOfWeekDateTime.format(formatter);
            String endOfWeekDateTimeStr = endOfWeekDateTime.format(formatter);
            String key = startOfWeekDateTimeStr + "_" + endOfWeekDateTimeStr;
            if (weekBoundariesMap.get(key) == null) {
                WeekBoundary boundary = new WeekBoundary(startOfWeekDateTime, endOfWeekDateTime);
                weekBoundaries.add(boundary);
                weekBoundariesMap.put(key, boundary);
            }
        }

        // 输出或处理结果
        weekBoundariesMap.forEach((k, v) -> {
            System.out.println("key " + k);
            System.out.println("Week Start: " + v.getStartOfWeek());
            System.out.println("Week End: " + v.getEndOfWeek());
        });
/*        for (WeekBoundary boundary : weekBoundaries) {
            System.out.println("Week Start: " + boundary.getStartOfWeek());
            System.out.println("Week End: " + boundary.getEndOfWeek());
        }*/
    }

    static class WeekBoundary {
        private LocalDateTime startOfWeek;
        private LocalDateTime endOfWeek;

        public WeekBoundary(LocalDateTime startOfWeek, LocalDateTime endOfWeek) {
            this.startOfWeek = startOfWeek;
            this.endOfWeek = endOfWeek;
        }

        // getters and setters
        public LocalDateTime getStartOfWeek() {
            return startOfWeek;
        }

        public LocalDateTime getEndOfWeek() {
            return endOfWeek;
        }
    }
}
